package com.miaoxie.service.crawl.impl;

import com.miaoxie.dao.crawl.INewsCrawlDatumDao;
import com.miaoxie.domain.crawl.NewsCrawlDatumEntity;
import com.miaoxie.service.crawl.INewsCrawlDatumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: miaoxie
 * Date: 2018-05-16
 * Time: 上午8:32
 */
@Service
public class NewsCrawlDatumServiceImpl implements INewsCrawlDatumService {
    @Autowired
    INewsCrawlDatumDao newsCrawlDatumDao;


    @Override
    public NewsCrawlDatumEntity creat(NewsCrawlDatumEntity entity) {
        return  newsCrawlDatumDao.save(entity);
    }

    @Override
    public List<NewsCrawlDatumEntity> findAll() {
        return newsCrawlDatumDao.findAll();
    }

    @Override
    public Optional<NewsCrawlDatumEntity> findById(String id) {
        return newsCrawlDatumDao.findById(id);
    }

    @Override
    public Page<NewsCrawlDatumEntity> findPage(Integer page, Integer size, String sortClom,String sortType) {
        Page<NewsCrawlDatumEntity> list = newsCrawlDatumDao.findAll(initPageable(page, size, sortClom, sortType));
        return list;
    }


    private Pageable initPageable(Integer page, Integer size, String sortClom,String sortType){
        Sort sort = null;
        Pageable pageable = null;
        if (!StringUtils.isEmpty(sortClom)){
            if (StringUtils.isEmpty(sortType) || sortType.equals("asc")){
                sort = new Sort(Sort.Direction.ASC, sortClom);
            }else {
                sort = new Sort(Sort.Direction.DESC, sortClom);
            }
        }
        if (sort == null){
            pageable = new PageRequest(page, size);
        }else {
            pageable = new PageRequest(page, size, sort);
        }
        return pageable;
    }
}
